package com.baiyang.server.control.system;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.baiyang.server.model.system.Route;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.baiyang.server.annotation.Jurisdiction;
import com.baiyang.server.model.PageEntity;
import com.baiyang.server.model.system.Role;
import com.baiyang.server.model.system.User;
import com.baiyang.server.service.system.RoleService;
import com.baiyang.server.service.system.UserService;
import com.baiyang.server.tools.Data;
import com.baiyang.server.tools.DataTool;
import com.baiyang.server.tools.GraphicHelper;
import com.baiyang.server.tools.Letter;
import com.baiyang.server.tools.SubjectNotNull;

@RestController
@RequestMapping(value = "/userOperation")
@Jurisdiction(value = "用户信息")
public class UserCon {
	@Autowired
	private UserService userService = null;
	@Autowired
	private RoleService roleService = null;
	/**
	 * 根绝条件分页获取数据
	 * @return
	 */
	@Jurisdiction(value = "批量读取")
	@RequestMapping(value = "/getPage",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<User> getPage(@RequestBody JSONObject object){
		Letter<User> letter = new Letter<User>();
		try {
			PageEntity<User> result = userService.getPage(object);
			if(!DataTool.isBlank(result.getDatas())) {
				result.getDatas().forEach(e->{
					List<Role> roles = roleService.selectRolesByUserId(e.getId());
					e.setRoles(roles);
				});
			}
			letter.setList(result.getDatas());
			letter.setTotal(result.getCount());
			letter.setDetail(result.getResult());
			letter.setResult("SUCCESS");
			letter.setDetail("数据获取成功！");
		}catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据获取失败！");
		}
		return letter;
	}


	/**
	 * 获取书币和积分
	 * @param user
	 * @return
	 */
	@Jurisdiction(value = "获取书币和积分")
	@RequestMapping(value = "/getBookCoinAndIntegral",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<JSONObject> getBookCoinAndIntegral(@RequestBody User user){
		Letter<JSONObject> letter = new Letter<JSONObject>();
		try {
			JSONObject obj = userService.getBookCoinAndIntegral(user);
			letter.setData(obj);
			letter.setDetail("数据获取成功");
			letter.setResult("SUCCESS");
		}catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据获取失败！");
		}
		return letter;
	}

	/**
	 * 根据条件获取一个用户信息
	 * @param user
	 * @return
	 */
	@Jurisdiction(value = "读取")
	@RequestMapping(value = "/selectOne",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<User> selectOne(@RequestBody User user){
		Letter<User> letter = new Letter<User>();
		try {
			User obj = userService.selectOne(user);
			letter.setData(obj);
			letter.setDetail("数据获取成功");
			letter.setResult("SUCCESS");
		}catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据获取失败！");
		}
		return letter;
	}
	
	
	/**
	 * 插入数据
	 * @param user
	 * @return
	 */
	@Jurisdiction(value = "新增")
	@RequestMapping(value = "/insert",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<String> insert(@RequestBody User user){
		Letter<String> letter = new Letter<String>();
		try {
			user.setId(DataTool.createUUID());
			if(user.getPassword()==null) {
				user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
			}else{
				user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
			}
			User u = new User();
			u.setUserName(user.getUserName());
			u = userService.selectOne(u);
			if(u!=null){
				letter.setResult("FAIL");
				letter.setDetail("用户名重复");
				return letter;
			}
			if(userService.insert(user)) {
				letter.setDetail("数据插入成功");
				letter.setResult("SUCCESS");
			}else {
				letter.setDetail("数据插入失败");
				letter.setResult("FAIL");
			}
		}catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据插入失败！");
		}
		return letter;
	}

	/**
	 * 插入数据
	 * @param user
	 * @return
	 */
	@Jurisdiction(value = "新增")
	@RequestMapping(value = "/readerRegister",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<User> readerRegister(@RequestBody User user){
		Letter<User> letter = new Letter<User>();
		try {
			user.setId(DataTool.createUUID());
			if(user.getPassword()==null) {
				user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
			}else{
				user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
			}
			User u = new User();
			u.setUserName(user.getUserName());
			u = userService.selectOne(u);
			if(u!=null){
				letter.setResult("FAIL");
				letter.setDetail("用户名重复");
				return letter;
			}
			userService.readerRegister(user);
			letter.setResult("SUCCESS");
			letter.setDetail("插入成功");
			letter.setData(user);
		}catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据插入失败！");
		}
		return letter;
	}

	/**
	 * 插入数据
	 * @param user
	 * @return
	 */
	@Jurisdiction(value = "作者注册")
	@RequestMapping(value = "/authorRegister",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<User> authorRegister(@RequestBody User user){
		Letter<User> letter = new Letter<User>();
		try {
			user.setId(DataTool.createUUID());
			if(user.getPassword()==null) {
				user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
			}else{
				user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
			}
			User u = new User();
			u.setUserName(user.getUserName());
			u = userService.selectOne(u);
			if(u!=null){
				letter.setResult("FAIL");
				letter.setDetail("用户名重复");
				return letter;
			}
			userService.authorRegister(user);
			letter.setResult("SUCCESS");
			letter.setDetail("插入成功");
			letter.setData(user);
		}catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据插入失败！");
		}
		return letter;
	}

	
	/**
	 * 批量插入数据
	 * @param users
	 * @return
	 */
	@Jurisdiction(value = "批量新增")
	@RequestMapping(value = "/insertBatch",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<String> insertBatch(@RequestBody List<User> users){
		Letter<String> letter = new Letter<String>();
		try {
			userService.insertBatch(users,letter);
			letter.setResult("SUCCESS");
			letter.setDetail("数据插入成功");
		}catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据插入失败！");
		}
		return letter;
	}
	
	/**
	 * 根绝条件进行删除
	 * @param user
	 * @return
	 */
	@Jurisdiction(value = "删除")
	@RequestMapping(value = "/delete",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<String> delete(@RequestBody User user){
		Letter<String> letter = new Letter<String>();
		if(SubjectNotNull.subjectIsNull(user)) {
			letter.setResult("FAIL");
			letter.setDetail("信息不能为空！");
			return letter;
		}
		try {
			userService.delete(user);
			letter.setDetail("数据删除成功");
			letter.setResult("SUCCESS");
		}catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据删除失败");
		}
		return letter;
	}

	/**
	 * 根绝条件进行删除
	 *
	 * @param users
	 * @return
	 */
	@Jurisdiction(value = "deletes")
	@RequestMapping(value = "/deletes", produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<String> deletes(@RequestBody List<User> users) {
		Letter<String> letter = new Letter<String>();
		if (DataTool.isBlank(users)) {
			letter.setResult("FAIL");
			letter.setDetail("请至少选中一行！");
			return letter;
		}
		try {
			userService.deletes(users);
			letter.setDetail("数据删除成功");
			letter.setResult("SUCCESS");
		} catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据删除成功！");
		}
		return letter;
	}
	
	/**
	 * 根绝id更新
	 * @param user
	 * @return
	 */
	@Jurisdiction(value = "修改")
	@RequestMapping(value = "/updateById",produces = MediaType.APPLICATION_JSON_VALUE)
	public Letter<String> updateById(@RequestBody User user){
		Letter<String> letter = new Letter<String>();
		if(user.getId().equals("")) {
			letter.setResult("FAIL");
			letter.setDetail("id不能为空！");
			return letter;
		}
		try {
			userService.updateById(user);
			letter.setDetail("数据更新成功");
			letter.setResult("SUCCESS");
		}catch (Exception e) {
			e.printStackTrace();
			letter.setResult("ERROR");
			letter.setDetail("数据更新失败！");
		}
		return letter;	
	}
	
	
	
	/**
	 * @author XVX
	 * @apiNote 返回图片验证码，并将验证码存储到session中用于验证
	 * @jurisdiction 任何用户皆可访问
	 * @care response.getOutputStream() 调用之后无法找不到Session ID，因此再调用getSession方法会报错“Cannot create a session after the response has been committed”
	 */
	@Jurisdiction(value = "获取验证码")
	@RequestMapping(value = "/getVerPic",produces = MediaType.APPLICATION_JSON_VALUE)
	public void getVerPic(HttpServletResponse response,HttpServletRequest request){
		try {
			Authentication authentication = SecurityContextHolder.getContext()
					.getAuthentication();
			
			HttpSession session = request.getSession();
			// 获取图片验证码将图片写入返回流中，并返回验证码
			String verCode = GraphicHelper.create(100, 40, "JPG", response.getOutputStream());
			// 将验证码信息写入到session中
			session.setAttribute(Data.Session.VER_CODE, verCode);
			System.out.println(verCode);
		} catch (IOException e) {
			e.printStackTrace();
		}
	} 
}

